package com.zmx.core.client.invokemethod;

import com.zmx.core.dto.RequestDataInfo;
import com.zmx.core.executor.JobExecutor;
import com.zmx.core.handler.MethodJobHandler;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Description: 监听队列执行任务
 * @ClassName: InvokeMethodByQueueListener
 * @Author zhaomxr
 * @Date 2021-12-17 16:48
 */
@Slf4j
public class InvokeMethodByQueueListener {

    private AtomicInteger runningJob = new AtomicInteger(0);

    public void start() {
        ThreadPoolExecutor bizThreadPool = new ThreadPoolExecutor(
                0,
                100,
                60L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<Runnable>(2000),
                new ThreadFactory() {
                    @Override
                    public Thread newThread(Runnable r) {
                        return new Thread(r, "mall-job, InvokeMethod bizThreadPool-" + r.hashCode());
                    }
                },
                new RejectedExecutionHandler() {
                    @Override
                    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
                        throw new RuntimeException("mall-job, InvokeMethod bizThreadPool is EXHAUSTED!");
                    }
                });

        int activeCount = bizThreadPool.getActiveCount();

        //如果线程池运行线程数小于100,将队列中任务放入线程池执行
        while (activeCount < 100) {
            bizThreadPool.execute(new Runnable() {
                @Override
                public void run() {
                    RequestDataInfo requestDataInfo = MethodQueue.poll();
                    if (requestDataInfo != null) {
                        String name = requestDataInfo.getValue();
                        try {
                            MethodJobHandler methodJobHandler = (MethodJobHandler) JobExecutor.loadJobHandler(name);
                            methodJobHandler.execute();
                        } catch (InvocationTargetException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            log.error("execute job faile MallJob is {}", name);
                            log.error(e.getMessage(), e);
                        }
                    }
                }
            });
        }

    }
}
